package de.pcsoft.framework.jclr;

import de.pcsoft.framework.jclr.exceptions.JCLRProcessException;

/**
 * JCLR Main Class for Framework
 * User: Christoph
 * Date: 13.06.12
 * Time: 19:39
 */
public class JCLR {

    /**
     * Starts the reading of the arguments and startup the main program over the listener.
     *
     * @param args          The command line arguments to use
     * @param configuration Configuration for argument reading
     * @return Returns the result of the argument reading
     * @throws JCLRProcessException Is thrown if an internal error is thrown
     */
    public static JCLRResult readCommandLineArguments(String[] args, JCLRConfiguration configuration) throws JCLRProcessException {
        JCLRResult lastResult = new JCLRResult();
        GroupDefinitionType argumentDefinition = configuration.getArgumentDefinition();
        SettingsType settings = configuration.getSettings();

        JCLRArgumentReadingUtils.scanForGroup(args, argumentDefinition, settings, lastResult);

        if (lastResult.hasError()) {
            printError(lastResult.getError());
            if (settings.getHelpSettings().isAlwaysShowHelp()) {
                System.out.println();
                printMainHelp(configuration);
            }
            System.out.println();
        }

        return lastResult;
    }

    public static void printError(JCLRError error) {
        System.out.println(getErrorString(error));
    }

    public static String getErrorString(JCLRError error) {
        return error.getErrorMessage() + " (" + error.getErrorType().name() + ")";
    }

    public static void printMainHelp(JCLRConfiguration configuration) {
        System.out.println(getMainHelpString(configuration));
    }

    public static String getMainHelpString(JCLRConfiguration configuration) {
        return JCLRHelpUtils.buildMainHelp(configuration.getArgumentDefinition(), configuration.getSettings());
    }
}
